package com.zktravel.service.user;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.zktravel.core.exception.VisibleException;
import com.zktravel.enums.CodeEnum;
import com.zktravel.mapper.ShopMapper;
import com.zktravel.model.dto.user.UserInfo;
import com.zktravel.model.po.Shop;
import com.zktravel.service.message.MessageSendService;
import com.zktravel.util.JsonHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    protected Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private MessageSendService messageSendService;
    @Resource
    private ShopMapper shopMapper;

    private static final String USER_URI = "/gate-user/w-app/get-user-info";

    @Override
    public UserInfo getUserInfo(Long uid) {
        UserInfo userInfo = new UserInfo();

        Map<String, String> parameters = ImmutableMap.of("uid", uid.toString());
        String jsonParams = JsonHelper.bean2Json(parameters);
        try {
            JSONObject jo = messageSendService.postRequest(USER_URI, jsonParams);
            if ("0".equals(jo.get("code")) || jo.get("code").equals(0)) {
                userInfo = JsonHelper.json2Bean(jo.get("info").toString(), UserInfo.class);
            }
            // TODO 关闭vip功能 临时处理 zkx 2018-06-28
            userInfo.getVipInfo().setFlag(false);
        } catch (Exception e) {
            this.logger.error("用户请求失败：{}", e);
        }

        return userInfo;
    }

    @Override
    public UserInfo getUserInfoByShopId(Long shopId) {
        //通过shopId获取店铺主人的信息
        Shop shop = shopMapper.selectByPrimaryKey(shopId);
        if (null == shopId) {
            throw new VisibleException(CodeEnum.SHOP_NOT_EXIST);
        }
        UserInfo userInfo = this.getUserInfo(shop.getUserId());
        if (null == userInfo) {
            throw new VisibleException(CodeEnum.USER_NOT_EXIST);
        }

        return userInfo;
    }
}
